import worker, { ThreadWorkerGlobalScope, MessageEvents, ErrorEvent } from '@ohos.worker';
import { getLabels, rawLabelsToString, stringToLabels } from '../util/fakeBart';

import nativeModule from 'libentry.so';
const workerPort: ThreadWorkerGlobalScope = worker.workerPort;

function debugLabel(labels: string[]) {
  for (let label of labels) {
    console.log("worker debug " + label)
  }
}

/**
 * Defines the event handler to be called when the worker thread receives a message sent by the host thread.
 * The event handler is executed in the worker thread.
 *
 * @param e message data
 */
workerPort.onmessage = function (e: MessageEvents) {
  switch (e.data.type as number) {
    case 0:
      {
        let labelSet = nativeModule.genLabels(e.data.text as string,e.data.labels as string)
        console.log("predict get label is " + labelSet)
        let labels = stringToLabels(labelSet)
        debugLabel(labels)
        workerPort.postMessage({type:0,id:e.data.id as number,labels:rawLabelsToString(labels)})
        break;
      }
    case 1:
      {
        // let opo = nativeModule.predict(e.data.text as string,
        //   e.data.textPair as string)
        workerPort.postMessage({type:1,value:12})
        break;
      }
  }
}

/**
 * Defines the event handler to be called when the worker receives a message that cannot be deserialized.
 * The event handler is executed in the worker thread.
 *
 * @param e message data
 */
workerPort.onmessageerror = function (e: MessageEvents) {
  switch (e.data.type as number) {
    case 0:
      {
        console.log("worker onmessage error")

        break;
      }
    case 1:
      {
        // let opo = nativeModule.predict(e.data.text as string,
        //   e.data.textPair as string)
        break;
      }
  }
}

/**
 * Defines the event handler to be called when an exception occurs during worker execution.
 * The event handler is executed in the worker thread.
 *
 * @param e error message
 */
workerPort.onerror = function (e: ErrorEvent) {
  console.log("worker error")
}